package com.swz.dcrm.ui;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.lifecycle.Observer;
import androidx.navigation.fragment.NavHostFragment;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Rect;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.Toast;

import com.flyco.dialog.listener.OnOperItemClickL;
import com.flyco.dialog.widget.ActionSheetDialog;
import com.flyco.tablayout.CommonTabLayout;
import com.flyco.tablayout.listener.CustomTabEntity;
import com.flyco.tablayout.listener.OnTabSelectListener;
import com.swz.dcrm.R;
import com.swz.dcrm.digger.AppModule;
import com.swz.dcrm.digger.DaggerAppComponent;
import com.swz.dcrm.model.BaseResponse;
import com.swz.dcrm.model.Input;
import com.swz.dcrm.model.WorkRemind;
import com.swz.dcrm.ui.MyApplication;
import com.swz.dcrm.ui.base.BaseActivity;
import com.swz.dcrm.ui.viewmodel.MainViewModel;
import com.swz.dcrm.ui.main.TabEntity;
import com.swz.dcrm.ui.viewmodel.TodayPlanViewModel;
import com.swz.dcrm.util.Constant;

import com.swz.dcrm.util.DateUtils;
import com.swz.dcrm.util.Tool;
import com.xh.baselibrary.util.AnimationUtil;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.ButterKnife;
import qiu.niorgai.StatusBarCompat;


public class MainActivity extends BaseActivity {

    @BindView(R.id.tabLayout)
    CommonTabLayout commonTabLayout;
    private ActionSheetDialog callDialog;
    private String[] titles=new String[]{};
    private String currentPhone;
    private Toast mToast;
    private InputMethodManager inputMethodManager;
    @Inject
    MainViewModel mainViewModel;
    @Inject
    TodayPlanViewModel todayPlanViewModel;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_activity);
        ButterKnife.bind(this);

        inputMethodManager= (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);

        DaggerAppComponent.builder().appModule(new AppModule(this))
                .build().inject(this);
        if (savedInstanceState == null) {

            titles=getResources().getStringArray(R.array.main_tab_name);
            ArrayList<CustomTabEntity> customTabEntities=new ArrayList<>();
            for(int i=0;i<titles.length;i++){

                switch (i){
                    case 0:
                        customTabEntities.add(new TabEntity(titles[i],R.mipmap.tab_home_on,R.mipmap.tab_home));
                        break;
                    case 1:
                        customTabEntities.add(new TabEntity(titles[i],R.mipmap.tab_message_on,R.mipmap.tab_message));
                        break;
                    case 2:
                        customTabEntities.add(new TabEntity(titles[i],R.mipmap.tab_user_on,R.mipmap.tab_user));
                        break;
                }


            }
            commonTabLayout.setTabData(customTabEntities);

            commonTabLayout.setOnTabSelectListener(new OnTabSelectListener() {
                @Override
                public void onTabSelect(int position) {
                    mainViewModel.getPageIndex().setValue(position);
                }

                @Override
                public void onTabReselect(int position) {

                }
            });



            mainViewModel.getShowTab().observe(this, aBoolean -> {
                if(aBoolean){
                    if(commonTabLayout.getVisibility()!= View.VISIBLE){
                        commonTabLayout.setAnimation(AnimationUtil.moveToViewLocation());
                        commonTabLayout.setVisibility(View.VISIBLE);
                    }
                }else {
                    if(commonTabLayout.getVisibility()==View.VISIBLE){
                        commonTabLayout.setAnimation(AnimationUtil.moveToViewBottom());
                        commonTabLayout.setVisibility(View.GONE);
                    }
                }
            });
            mainViewModel.getCall().observe(this,phone -> {
                 currentPhone=phone;
                 callDialog=new ActionSheetDialog(this,new String[]{getString(R.string.call,currentPhone)},null);
                 callDialog.setOnOperItemClickL((parent, view, position, id) -> {
                     if (position==0){
                        call(this,currentPhone);
                     }
                 });
                 callDialog.isTitleShow(false);
                 callDialog.show();
            });
            mainViewModel.getInput().observe(this, input -> {
                if(input.isShow()){
                    inputMethodManager.showSoftInput(input.getView(),input.getFlag());
                }else {
                    inputMethodManager.hideSoftInputFromWindow(input.getView().getWindowToken(),input.getFlag());
                }
            });
        }

    }




    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {

        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            Rect outRect = new Rect();
            if(mainViewModel.getInput().getValue()!=null&&mainViewModel.getInput().getValue().getView()!=null){
                mainViewModel.getInput().getValue().getView().getGlobalVisibleRect(outRect);//如果点击除该view 其他隐藏这个view
                if (!outRect.contains((int)ev.getRawX(), (int)ev.getRawY())) {
                    if(inputMethodManager.isActive(mainViewModel.getInput().getValue().getView())){
                        inputMethodManager.hideSoftInputFromWindow(mainViewModel.getInput().getValue().getView().getWindowToken(),
                                mainViewModel.getInput().getValue().getFlag());
                    }else {

                    }

                }
            }
            Rect out =new Rect();
            if(mainViewModel.getInput().getValue()!=null&&mainViewModel.getInput().getValue().getNeedGone()!=null){
                mainViewModel.getInput().getValue().getNeedGone().getGlobalVisibleRect(out);
                if (!out.contains((int)ev.getRawX(), (int)ev.getRawY())) {
                    mainViewModel.getInput().getValue().getNeedGone().setVisibility(View.GONE);
                }
            }


        }
        return super.dispatchTouchEvent(ev);
    }

    @Override
    protected void onResume() {
        super.onResume();
        todayPlanViewModel.getWorkRemind().observe(this, observer);
    }

    Observer observer=new Observer<BaseResponse<List<WorkRemind>>>() {
        @Override
        public void onChanged(BaseResponse<List<WorkRemind>> listBaseResponse) {
                if(listBaseResponse.isSuccess()){
                    int count=0;
                    if(listBaseResponse.getData().size()>0){
                        for(WorkRemind workRemind:listBaseResponse.getData()){
                            if(DateUtils.dateFormat(workRemind.getTime(),"yyyy-MM-dd").equals(DateUtils.getCurrentDate())){
                                count+=workRemind.getCount();
                            }                        }
                    }
                    if(count>0){
                        commonTabLayout.showDot(1);
                    }else {
                        commonTabLayout.hideMsg(1);
                    }
                }
        }
    };

    @Override
    public void onBackPressed() {
        NavHostFragment fragment = (NavHostFragment) getSupportFragmentManager().findFragmentById(R.id.frame);


        if( fragment.getChildFragmentManager().getBackStackEntryCount()==0){
            moveTaskToBack(true);
        }else {
            NavHostFragment.findNavController(fragment).navigateUp();
        }

    }
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {

            case Constant.CALL_PHONE:
                if(callDialog!=null){
                    callDialog.dismiss();
                }
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                    call(this, currentPhone);

                } else {
                    // 被禁止授权
                    showToast( "请至权限中心打开本应用的电话权限");
                }
                break;
        }
    }
    public void showToast(String s){
        mToast= Toast.makeText(this,s,Toast.LENGTH_SHORT);
        mToast.setGravity(Gravity.CENTER,0,0);
        mToast.show();
    }
    public static void call(Activity activity, String phone) {


        if (ContextCompat.checkSelfPermission(activity, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
            // 申请权限
            ActivityCompat.requestPermissions(activity,new String[]{Manifest.permission.CALL_PHONE}, Constant.CALL_PHONE);
            return;
        }
        Intent intent = new Intent(Intent.ACTION_CALL);
        Uri data = Uri.parse("tel:" +phone);
        intent.setData(data);
        activity.startActivity(intent);
    }
}
